package edu.xjdx.os.controller;

import com.github.pagehelper.PageHelper;
import edu.xjdx.os.domain.*;
import edu.xjdx.os.domain.Dictionary;
import edu.xjdx.os.service.CartService;
import edu.xjdx.os.service.CustomerService;
import edu.xjdx.os.service.DictionaryService;
import edu.xjdx.os.service.GoodsService;
import edu.xjdx.os.utils.IDGenerator;
import edu.xjdx.os.utils.PageUtil;
import edu.xjdx.os.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CartService cartService;

    @GetMapping("/listAll")
    public String listAll(Model model) {
        List<Goods> goodsList = goodsService.listAll();
        for (Goods goods : goodsList) {
            goods.setGoodsCategory(dictionaryService.findById(goods.getGoodsCategory()).getDictionaryValue());
        }
        model.addAttribute("goods", goodsList);
        List<Dictionary> dictionaries = dictionaryService.findByName("商品类型");
        model.addAttribute("goodsCategory", dictionaries);
        return "back/goods_list";
    }

    @GetMapping("shopList")
    public String listAll(Model model, String orderType, Integer pageNum) {
        PageHelper.startPage(pageNum, 8);
        List<Goods> goodsList = goodsService.orderList(orderType);
        Pages pages = PageUtil.getPageInfo(goodsList);
        for (Goods goods : goodsList) {
            goods.setGoodsCategory(dictionaryService.findById(goods.getGoodsCategory()).getDictionaryValue());
        }
        String mothod = "shopList";
        model.addAttribute("method", mothod);
        model.addAttribute("orderType", orderType);
        model.addAttribute("pages", pages);
        model.addAttribute("goods", goodsList);
        return "fore/shop";
    }

    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
        goodsService.remove(id);
        Map<String, Object> map = new HashMap<>();
        map.put("ok", true);
        return map;
    }

    @PostMapping("/modify")
    public String modify(Goods goods, @RequestParam("file") MultipartFile file) throws IOException {

        Dictionary dictionary = dictionaryService.findById(goods.getGoodsCategory());
        goods.setGoodsCategory(dictionary.getDictionaryId());
        if (file != null) {
            String filename = file.getOriginalFilename();
            goods.setGoodsPicture(filename);
            UploadUtil.uploadFile(file);
        }
        goodsService.modify(goods);
        return "redirect:/goods/listAll";
    }

    @GetMapping("/add")
    public String add(Model model) {
        List<Dictionary> dictionaries = dictionaryService.findByName("商品类型");
        model.addAttribute("goodsCategory", dictionaries);
        return "back/goods_add";
    }

    @PostMapping("/add")
    public String add(Goods goods, @RequestParam("file") MultipartFile file) throws IOException {
        File fileDir = UploadUtil.getImgDirFile();
        Dictionary dictionary = dictionaryService.findById(goods.getGoodsCategory());
        goods.setGoodsId(IDGenerator.getId());
        goods.setGoodsSold("0");
        goods.setGoodsCategory(dictionary.getDictionaryId());
        UploadUtil.uploadFile(file);
        String filename = file.getOriginalFilename();
        goods.setGoodsPicture(filename);
        goodsService.add(goods);
        return "redirect:/goods/listAll";
    }

    @GetMapping("findByKeyword")
    public String findByKeyword(Model model, String keyword, String orderType, Integer pageNum) {
        PageHelper.startPage(pageNum, 8);
        List<Goods> goodsList = goodsService.findByKeyword(keyword, orderType);
        Pages pages = PageUtil.getPageInfo(goodsList);
        for (Goods goods : goodsList) {
            goods.setGoodsCategory(dictionaryService.findById(goods.getGoodsCategory()).getDictionaryValue());
        }
        String method = "findByKeyword";
        model.addAttribute("method", method);
        model.addAttribute("keyword", keyword);
        model.addAttribute("orderType", orderType);
        model.addAttribute("pages", pages);
        model.addAttribute("goods", goodsList);
        return "fore/find_result";
    }

    @GetMapping("findByCategory")
    public String findByCategory(Model model, String keyword, String orderType, Integer pageNum) {
        String category = dictionaryService.findByValue(keyword).getDictionaryId();
        PageHelper.startPage(pageNum, 8);
        List<Goods> goodsList = goodsService.findByCategory(category, orderType);
        Pages pages = PageUtil.getPageInfo(goodsList);
        for (Goods goods : goodsList) {
            goods.setGoodsCategory(dictionaryService.findById(goods.getGoodsCategory()).getDictionaryValue());
        }
        String mothod = "findByCategory";
        model.addAttribute("method", mothod);
        model.addAttribute("keyword", keyword);
        model.addAttribute("orderType", orderType);
        model.addAttribute("pages", pages);
        model.addAttribute("goods", goodsList);
        return "fore/find_result";
    }

    @PostMapping("addToCart")
    @ResponseBody
    public Object addToCart(String id, Integer amount, HttpSession session) {
        Goods goods = goodsService.findById(id);
        String id1=(String) session.getAttribute("customerId");
        Customer customer = customerService.findById(id1);
        cartService.add(customer, goods, amount);
        Map<String, Object> map = new HashMap<>();
        map.put("ok", true);
        return map;
    }

    @GetMapping("detail")
    public String detail(Model model, String id) {
        Goods goods = goodsService.findById(id);
        Dictionary dictionary = dictionaryService.findById(goods.getGoodsCategory());
        goods.setGoodsCategory(dictionary.getDictionaryValue());
        model.addAttribute("goods", goods);
        return "fore/shop-detail";
    }

    @GetMapping("statistics")
    public String showChart(Model model) {
        StringBuffer lables=new StringBuffer();
        StringBuffer datas=new StringBuffer();
        StringBuffer inventory=new StringBuffer();
        List<Dictionary> dictionaries=dictionaryService.findByName("商品类型");
        Map<String,Integer> map=new HashMap();
        Map<String,Integer> map1=new HashMap<>();
        List<Goods> goodsList=goodsService.listAll();
        for (Goods goods:goodsList){
            for (Dictionary dictionary:dictionaries){
                if (goods.getGoodsCategory().equals(dictionary.getDictionaryId())){
                    if (map.get(dictionary.getDictionaryValue())!=null){
                        map.put(dictionary.getDictionaryValue(),map.get(dictionary.getDictionaryValue())+1);
                    }else {
                        map.put(dictionary.getDictionaryValue(),1);
                    }
                    if (map1.get(dictionary.getDictionaryValue())!=null){
                        map1.put(dictionary.getDictionaryValue(),map1.get(dictionary.getDictionaryValue())+Integer.parseInt( goods.getGoodsInventory()));
                    }else {
                        map1.put(dictionary.getDictionaryValue(),Integer.parseInt( goods.getGoodsInventory()));
                    }
                }
            }
        }
        Set<String> set=map.keySet();
        for (String str:set){
            lables.append(str+",");
            datas.append(map.get(str)+",");
            inventory.append(map1.get(str)+",");
        }
        lables.deleteCharAt(lables.length()-1);
        datas.deleteCharAt(datas.length()-1);
        inventory.deleteCharAt(inventory.length()-1);
        model.addAttribute("datas",datas);
        model.addAttribute("lables",lables);
        model.addAttribute("inventory",inventory);
        return "back/goods_chart_test";
    }
}
